<template>
  <div class="user-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 第一行：状态筛选 -->
        <el-form-item label="用户状态">
          <el-radio-group v-model="searchForm.status" @change="handleStatusChange">
            <el-radio-button :label="UserStatus.ALL">全部人员</el-radio-button>
            <el-radio-button :label="UserStatus.PENDING">未允许参会</el-radio-button>
            <el-radio-button :label="UserStatus.APPROVED">已允许参会</el-radio-button>
            <el-radio-button :label="UserStatus.UNSIGNED">未签到</el-radio-button>
            <el-radio-button :label="UserStatus.SIGNED">已签到</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 第二行：名称和类型筛选 -->
        <el-form-item label="会议ID">
          <el-input
            v-model="searchForm.meetId"
            placeholder="请输入会议ID"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-upload
            class="qr-upload"
            :show-file-list="false"
            :auto-upload="true"
            :on-change="handleQRCodeUpload"
            accept="image/*"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>二维码签到
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">用户列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <div class="header-operations">
            <el-tooltip :content="selectedUsers.length ? '允许选中的用户参会' : '请先选择要允许参会的用户'" placement="top">

            </el-tooltip>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>导出数据
            </el-button>
            <el-button 
              type="primary"
              :disabled="!selectedUsers.length || !hasPendingUsers"
              @click="handleBatchApprove"
            >
              <el-icon><Check /></el-icon>
              批量允许 {{ selectedUsers.length ? `(${selectedUsers.length})` : '' }}
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedUsers.length || !hasPendingUsers"
              @click="handleBatchReject"
            >
              <el-icon><Close /></el-icon>
              批量拒绝 {{ selectedUsers.length ? `(${selectedUsers.length})` : '' }}
            </el-button>
          </div>
        </div>
      </template>
      <el-table 
        :data="userList" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="nickname" label="昵称" min-width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              {{ row.nickname }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="meetId" label="会议ID" width="120">
          <template #default="{ row }">
            {{ row.meetId }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请理由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getUserStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="absenceReason" label="缺席原因" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.status === UserStatus.UNSIGNED && row.absenceReason">
              <el-tooltip :content="row.absenceReason" placement="top">
                <el-button type="warning" link>查看原因</el-button>
              </el-tooltip>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === UserStatus.PENDING"
              type="primary" 
              link 
              @click="handleApprove(row)"
            >
              允许参会
            </el-button>
            <el-button 
              v-if="row.status === UserStatus.PENDING"
              type="danger" 
              link 
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
            <el-button 
              v-if="row.status === UserStatus.APPROVED || row.status === UserStatus.UNSIGNED"
              type="success" 
              link 
              @click="handleSignIn(row)"
            >
              签到
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="昵称">{{ currentUser?.nickname }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentUser?.status || UserStatus.PENDING)">
            {{ getUserStatusLabel(currentUser?.status || UserStatus.PENDING) }}
          </el-tag>
        </el-descriptions-item>
        <!-- <el-descriptions-item label="公司">{{ currentUser?.company }}</el-descriptions-item> -->
        <!-- <el-descriptions-item label="职位">{{ currentUser?.position }}</el-descriptions-item> -->
        <el-descriptions-item label="手机号">{{ currentUser?.phone }}</el-descriptions-item>
        <el-descriptions-item label="会议ID">
          {{ currentUser?.meetId }}
        </el-descriptions-item>
        <el-descriptions-item label="申请理由" :span="2">
          {{ currentUser?.reason }}
        </el-descriptions-item>
        <el-descriptions-item v-if="currentUser?.absenceReason" label="缺席原因" :span="2">
          {{ currentUser?.absenceReason }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 缺席原因对话框 -->
    <!-- <el-dialog
      v-model="absenceDialogVisible"
      title="记录缺席原因"
      width="500px"
    >
      <el-form :model="absenceForm" label-width="100px">
        <el-form-item label="缺席原因" required>
          <el-input
            v-model="absenceForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入缺席原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="absenceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAbsence">确定</el-button>
      </template>
    </el-dialog> -->

    <!-- 拒绝原因对话框 -->
    <!-- <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝申请"
      width="500px"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitReject">确定</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Check, Close, Search, Refresh, Upload } from '@element-plus/icons-vue'
import { getUserList, approveUser, signInUser, rejectUser, batchApproveUsers, batchRejectUsers, exportUserData, signInWithQRCode } from '@/api/user'
import type { UserMeetingRecord, ListUserResponse } from '@/api/user'
import { UserStatus } from '@/api/user'

// 定义用户类型
type User = UserMeetingRecord

// 搜索表单
const searchForm = reactive({
  meetId: undefined as string | undefined,
  status: UserStatus.ALL,
})

// 状态相关
const loading = ref(false)
const userList = ref<User[]>([])
const selectedUsers = ref<User[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const currentUser = ref<User>()

// 对话框相关
const detailDialogVisible = ref(false)
const absenceDialogVisible = ref(false)
const rejectDialogVisible = ref(false)

// 表单数据
const absenceForm = reactive({
  reason: ''
})

const rejectForm = reactive({
  reason: ''
})

// 获取状态标签类型
const getStatusTagType = (status?: UserStatus): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const map: Record<UserStatus, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    [UserStatus.ALL]: '',
    [UserStatus.PENDING]: 'warning',
    [UserStatus.APPROVED]: 'success',
    [UserStatus.UNSIGNED]: 'info',
    [UserStatus.SIGNED]: 'success'
  }
  return status ? map[status] : ''
}

// 获取用户状态显示文本
const getUserStatusLabel = (status: UserStatus): string => {
  const map: Record<UserStatus, string> = {
    [UserStatus.ALL]: '全部人员',
    [UserStatus.PENDING]: '未允许参会',
    [UserStatus.APPROVED]: '已允许参会',
    [UserStatus.UNSIGNED]: '未签到',
    [UserStatus.SIGNED]: '已签到'
  }
  return map[status] || '未知状态'
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = (await getUserList({
      page: currentPage.value,
      size: pageSize.value,
      meetId: searchForm.meetId,
      status: searchForm.status === UserStatus.ALL ? undefined : searchForm.status,
    })) as ListUserResponse
    userList.value = response.current_data
    total.value = response.total_record
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.meetId = undefined
  searchForm.status = UserStatus.ALL
  handleSearch()
}

// 状态切换
const handleStatusChange = () => {
  handleSearch()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUserList()
}

// 允许参会
const handleApprove = async (row: User) => {
  try {
    await approveUser({
      phone: row.phone,
      meetId: row.meetId
    })
    ElMessage.success('已允许参会')
    fetchUserList()
  } catch (error) {
    console.error('允许参会失败:', error)
    ElMessage.error('允许参会失败')
  }
}

// 拒绝申请
const handleReject = async (row: User) => {
  try {
    await rejectUser({
      phone: row.phone,
      meetId: row.meetId
    })
    ElMessage.success('已拒绝申请')
    fetchUserList()
  } catch (error) {
    console.error('拒绝申请失败:', error)
    ElMessage.error('拒绝申请失败')
  }
}

// 签到
const handleSignIn = async (row: User) => {
  try {
    await signInUser({
      phone: row.phone,
      meetId: row.meetId
    })
    ElMessage.success('签到成功')
    fetchUserList()
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  }
}

// 查看用户详情
const handleViewDetail = (row: User) => {
  currentUser.value = row
  detailDialogVisible.value = true
}

// 处理表格选择
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
}

// 导出数据
const handleExport = async () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请选择要导出的用户')
    return
  }

  try {
    const ids = selectedUsers.value.map(user => user.id)
    console.log('准备导出的用户ID:', ids)
    const response = await exportUserData(ids)
    
    // 调试日志
    console.log('导出响应:', response)
    
    // 直接使用响应的 Blob
    if (response instanceof Blob) {
      const downloadUrl = window.URL.createObjectURL(response)
      const downloadLink = document.createElement('a')
      downloadLink.href = downloadUrl
      downloadLink.download = '用户数据.xlsx'
      document.body.appendChild(downloadLink)
      downloadLink.click()
      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(downloadUrl)
      ElMessage.success('导出成功')
    } else {
      throw new Error('导出失败：响应格式不正确')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 批量允许参会
const handleBatchApprove = async () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请选择要允许参会的用户')
    return
  }

  try {
    const records = selectedUsers.value.map(user => ({
      phone: user.phone,
      meetId: user.meetId
    }))
    await batchApproveUsers({ records })
    ElMessage.success('批量允许参会成功')
    selectedUsers.value = []
    fetchUserList()
  } catch (error) {
    console.error('批量允许参会失败:', error)
    ElMessage.error('批量允许参会失败')
  }
}

// 批量拒绝申请
const handleBatchReject = async () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请选择要拒绝的用户')
    return
  }

  try {
    const records = selectedUsers.value.map(user => ({
      phone: user.phone,
      meetId: user.meetId
    }))
    await batchRejectUsers({ records })
    ElMessage.success('批量拒绝申请成功')
    selectedUsers.value = []
    fetchUserList()
  } catch (error) {
    console.error('批量拒绝申请失败:', error)
    ElMessage.error('批量拒绝申请失败')
  }
}

// 计算是否有待审核的用户
const hasPendingUsers = computed(() => {
  return selectedUsers.value.some(user => user.status === UserStatus.PENDING)
})

// 二维码签到处理
const handleQRCodeUpload = async (file: any) => {
  try {
    await signInWithQRCode(file.raw)
    ElMessage.success('签到成功')
    fetchUserList()
  } catch (error) {
    console.error('二维码签到失败:', error)
    ElMessage.error('签到失败')
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.user-management {
  .avatar-container {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .avatar-placeholder {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    border-radius: 50%;
    color: #909399;
  }

  .user-upload {
    @extend .upload-container;
  }

  .qr-upload {
    margin-right: 16px;
  }
}
</style> 